/*
 * 文件名：LogInterceptor.java
 * 版权：Copyright by www.nd.com
 * 描述：
 * 修改人：Administrator
 * 修改时间：2016年10月9日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.wmzdq.config;

import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//打印接收到的请求日志
public class LogInterceptor implements HandlerInterceptor
{
    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler)
        throws Exception
    {
        StringWriter sw = new StringWriter();
        sw.append("<request>\t" + request.getMethod() + "\turl:" + request.getRequestURL() + "\theads:");
        Enumeration<String> it = request.getHeaderNames();
        while (it.hasMoreElements()) {
            String key = it.nextElement();
            sw.append(key).append("=").append(request.getHeader(key)).append("&");
        }

        sw.append("\tparams:");

        if (CollectionUtils.isEmpty(request.getParameterMap())) {
            sw.append("NONE");
        } else {
            for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                for (String value : entry.getValue()) {
                    sw.append(entry.getKey()).append("=").append(value).append("&");
                }
            }
        }
        
        if(logger.isInfoEnabled()){
            logger.info(sw.toString());
        }
        
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView)
        throws Exception
    {
        // TODO Auto-generated method stub
        
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
        throws Exception
    {
        logger.info("<response>\t" + request.getMethod() + "\turl:" + request.getRequestURL() + "\tstatusCode:" + response.getStatus() + "\tcontent-type:" + response.getContentType() + "\texception:" + (ex == null ? "NONE" : ex.getMessage()));
        
    }

   

}
